package br.com.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.util.Scanner;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.http.client.ClientProtocolException;

import br.com.robot.RobotConfigurationBasic;

public class SCLoader
{
    public static Invocable load( String scFile ) throws ScriptException, NoSuchMethodException, ClientProtocolException, IOException
    {
        ScriptEngineManager factory = new ScriptEngineManager( );
        ScriptEngine        engine  = factory.getEngineByName( "javascript" );
        
        engine.put( "config", new RobotConfigurationBasic( ) );
        
        engine.eval( obtemArquivo( scFile ) );
        Invocable invocable = (Invocable)engine;
        
        return invocable;
//        invocable.invokeFunction( "init" );
    }

    private static StringReader obtemArquivo( String scFile ) throws FileNotFoundException
    {
        String basics = lerArquivo( scFile );
        String demosc = lerArquivo( "demosc.js" );
        
        return new StringReader( basics.concat( "\n".concat( demosc ) ) );
    }
    
    private static String lerArquivo( String arq ) throws FileNotFoundException
    {
        StringBuilder sb = new StringBuilder( );
        
        Scanner sc = new Scanner( new File( arq ) );
        
        while( sc.hasNextLine( ) )
        {
            sb.append( sc.nextLine( ) );
        }
        
        sc.close( );
        
        return sb.toString( );
    }
    
    public static Object carregaFuncao( Invocable invok, String funcao )
    {
        try
        {
            return invok.invokeFunction( funcao );
        }
        catch( NoSuchMethodException e )
        {
            e.printStackTrace( );
        } 
        catch( ScriptException e )
        {
            e.printStackTrace( );
        }
        
        return null;
    }
}